package com.wps.wdztv6.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.wps.wdztv6.api.common.TemplateFileEnum;
import com.wps.wdztv6.common.BusinessExceptionEnum;
import com.wps.wdztv6.common.Err;
import com.wps.wdztv6.common.R;
import com.wps.wdztv6.config.WdztAppinfoProperties;
import com.wps.wdztv6.entity.TemplateFile;
import com.wps.wdztv6.mapper.TemplateFileMapper;
import com.wps.wdztv6.service.TemplateFileService;
import com.wps.wdztv6.service.UserInfoService;
import com.wps.wdztv6.utils.WPS4Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 服务层实现。
 *
 * @author lhl
 * @since 2023-11-01
 */
@Validated
@Service
public class TemplateFileServiceImpl extends ServiceImpl<TemplateFileMapper, TemplateFile> implements TemplateFileService {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public R<TemplateFile> saveTemplateFile(TemplateFile templateFile, String token) {

        //userInfoService.saveUser(token); //todo

        MultipartFile file = templateFile.getFile();
        if (file != null) {
            //原始名,转小写
            String originalFilename = file.getOriginalFilename();
            templateFile.setFileSize(file.getSize() / 1024);
            //后缀
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf('.'));
            if (StrUtil.isBlank(fileExtension)) {
                throw Err.BusinessException.builder().code(BusinessExceptionEnum.FILESAVE_ERR2.getCode()).msg(BusinessExceptionEnum.FILESAVE_ERR2.getDescribe()).build();
            }
            templateFile.setFileExtension(fileExtension);

            //没送时取文件上的
            if (StrUtil.isBlank(templateFile.getTemplateFileName())) {
                templateFile.setTemplateFileName(originalFilename.substring(0, originalFilename.lastIndexOf('.')));
            }

            //新文件名 防重名
            File templateFilePathFolder = new File(WdztAppinfoProperties.templateFilePath);
            String fileurl = templateFilePathFolder.getAbsolutePath() + File.separator + WPS4Util.getOrderedSequence() + templateFile.getFileExtension();
            templateFile.setFileUrl(fileurl);

            try {
                //transferTo重名会覆盖
                file.transferTo(new File(templateFile.getFileUrl()));
            } catch (IOException e) {
                throw Err.BusinessException.builder().code(BusinessExceptionEnum.FILESAVE_ERR.getCode()).msg(BusinessExceptionEnum.FILESAVE_ERR.getDescribe()).build();
            }
        } else {
            //判断id不能空
            Integer fileId = templateFile.getId();
            if (fileId == null) {
                throw Err.BusinessException.builder().code(BusinessExceptionEnum.FILESAVE_ERR.getCode()).msg("请选择文件上传").build();
            }
        }

        //先保存记录
        boolean saved = this.saveOrUpdate(templateFile);

        if (saved) {
            return R.success(this.getById(templateFile.getId()));
        }
        return R.failed("保存失败");
    }


    @Override
    public void createTemplateBase(TemplateFileEnum templateFileEnum) throws IOException {

        TemplateFile build = TemplateFile.builder()
                .code(templateFileEnum.getCode())
                .templateFileName(templateFileEnum.getTemplateFileName())
                .source("wps")
                .fileExtension("." + templateFileEnum.getCode())
                .category("0")
                .fileSize(5L)
                .fileUrl(WdztAppinfoProperties.templateFilePath() + templateFileEnum.getOriginalFilename())
                .build();

        this.save(build);

        String classpathTemplate = "classpath:templates" + File.separator + "docs" + File.separator + templateFileEnum.getOriginalFilename();
        Resource resource = resourceLoader.getResource(classpathTemplate);

        FileUtil.writeFromStream(resource.getInputStream(), build.getFileUrl());

    }

    @Override
    public void removeByIdsAndFiles(List<Integer> ids, String token) {

        //userInfoService.saveUser(token); //todo

        List<TemplateFile> templateFiles = this.listByIds(ids);

        this.removeByIds(ids);

        for (TemplateFile templateFile : templateFiles) {
            FileUtil.del(templateFile.getFileUrl());
        }
    }


}
